// pages/shop/delivery.js
var app = getApp();
Page({
  data: {
    isthreshold: false,
    isDeliveryFree: false
  },
  onLoad: function (options) {
  
  },
  onReady: function () {
  
  },
  onShow: function(){
    var that = this;
    app.func.req('shops/show', {
      id: wx.getStorageSync('shop').id
    }, 'GET', function (res) {
      that.setData({
        shop: res.result,
        isthreshold: res.result.is_threshold == 1,
        isDeliveryFree: res.result.delivery_free > 0
      });
    }, {
        'token': wx.getStorageSync('token')
      });
  },
  save: function(e){
    var that = this;
    var isthreshold = this.data.isthreshold;
    var threshold = e.detail.value.threshold;
    var threshold_rebate = e.detail.value.threshold_rebate;
    var isDeliveryFree = this.data.isDeliveryFree;
    var delivery_free = e.detail.value.delivery_free > 0 ? e.detail.value.delivery_free : 0
    if (!isDeliveryFree) delivery_free = 0;
    if (isthreshold) {
      if ((!threshold || !threshold_rebate)) {
        wx.showModal({
          title: '提示',
          content: '请填写满减',
          showCancel: false,
        });
        return;
      }
      isthreshold = 1;
    } else {
      isthreshold = 0;
    }
    if (isDeliveryFree && e.detail.value.delivery_free == 0){
      wx.showModal({
        title: '提示',
        content: '请填写满X包邮',
        showCancel: false,
      });
      return;
    }

    app.func.req('shops/update', {
      start_delivery_amount: e.detail.value.start_delivery_amount,
      delivery_amount: e.detail.value.delivery_amount,
      delivery_free: delivery_free,
      is_threshold: isthreshold,
      threshold: threshold,
      threshold_rebate: threshold_rebate
    }, 'POST', function (res) {
      console.log(res)
      if (res.code == 'success') {
        wx.showToast({
          title: '保存成功',
          duration: 3000,
          success: function () {
            wx.switchTab({
              url: './shop'
            })
          }
        });
      } else {
        wx.showToast({
          title: '保存失败',
          image: '/images/fail.png',
          duration: 3000
        })
      }
    }, {
        'token': wx.getStorageSync('token')
      });
  },
  dothreshold: function (e) {
    this.setData({
      isthreshold: e.detail.value
    });
  },
  doDeliveryFree: function (e) {
    this.setData({
      isDeliveryFree: e.detail.value
    });
  },
})